06. Queues
Queues
ND079 C1 L6 A06 Queues
Sometimes we need to process items in a First-In, First-Out (FIFO) order.
Queues are data structures that allow us to process items in a First-In, First-Out (FIFO) order. The first item placed in a queue is also the first one removed from the queue.
An everyday example is a line at the grocery story, where the first customer to arrive at the checkout counter should be the first person to leave the store. There are many analogous cases in computer programs, such as when we have a list of processes and need to execute them in the order they arrive.
Some key points about Queues in Java:
- Queue is an interface that implements the Collection interface
- We put newly added elements at the end of the queue
- We pop elements off the front of the queue
Queues Syntax
For your reference, here are some basic syntax examples for creating and using queues.
Creating a Queue object
In the collections framework the Queue is an interface and cannot be directly used to instantiate a class. In the example below, we are creating a Queue of strings. Notice that we are using the concrete class LinkedList
to instantiate our Queue.
Queue<String> myQueue = new LinkedList<String>();
Adding to a Queue
Next we will look at adding objects to our Queue. In the example below we are adding Strings to our Queue using the add
method.
myQueue.add("Hi");
myQueue.add("There");
Retrieving an Object From a Queue
In this example we will be looking at the syntax to retrieve a String object from our Queue. Remember, Queues are First-In, First-Out (FIFO) data structures. So the first object in the queue will also be the first object out of the queue. We retrieve objects from our queue by using the poll
method. This method both retrieves the first element from the Queue and removes it from the Queue.
myQueue.poll()
Iterating Over a Queue
In our final example we will be looking at using the while
loop to iterate over our Queue and remove all of the elements. In the example below we are displaying all of the elements that were in the queue.
while (!myQueue.isEmpty()) {
System.out.println(myQueue.poll());
}
SOLUTION:
- Queues insert to the end of the Queue and pull from the top of the queue.
- Queues support all of the methods of the Collection interface.
- Queues follow a First in and First out (FIFO) concept.